import React, { Component } from 'react';
import { Form, Input, Button, message, Col, Row, Upload, Modal, Transfer,Tag, Tooltip, TreeSelect} from 'antd';
import { PlusOutlined, } from '@ant-design/icons';
import { connect } from 'dva'
import styles from './createSpecialTopic.less'
import * as requesturl from "@/services/request-url";

const { TextArea } = Input

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
@connect()
class CreateSpecialTopicForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            form: {
                name: "",
                introduction: "",

            },//表单数据
            // logo: "",
            // cover: "",
            previewVisible: false,
            previewImage: '',
            previewTitle: '',
            previewVisible2: false,
            previewImage2: '',
            previewTitle2: '',
            fileList: [],//封面
            fileList2: [],//logo
            //资产
            keywordData: [],
            targetKeys: [],
            //科研软件
            keywordData2: [],
            targetKeys2: [],
            formloading: false,
            tags: [],//关键字
            inputVisible: false,
            inputValue: '',
            editInputIndex: -1,
            editInputValue: '',
        }
    }
    //封面
    handleCancel1 = () => this.setState({ previewVisible: false });
    handleChange1 = ({ file, fileList }) => {
        console.log(file.response)
        if(file.response&&file.response.code==="403"){
            let a = document.createElement("a")
            a.href = `${requesturl.login}/cas/jwt/login.do`;
            a.click();
        }
        if (file.status === "done") this.setState({ cover: file.response.data })
        this.setState({ fileList })
    };
    handlePreview1 = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };
    //logo
    handleCancel2 = () => this.setState({ previewVisible2: false });
    handleChange2 = ({ file, fileList }) => {
        console.log(file.response)
        if(file.response&&file.response.code==="403"){
            let a = document.createElement("a")
            a.href = `${requesturl.login}/cas/jwt/login.do`;
            a.click();
        }
        if (file.status === "done") this.setState({ logo: file.response.data })
        this.setState({ fileList2: fileList })
    };
    handlePreview2 = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage2: file.url || file.preview,
            previewVisible2: true,
            previewTitle2: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };
    //关键字标签
    handleClose = removedTag => {
        const tags = this.state.tags.filter(tag => tag !== removedTag);
        console.log(tags);
        this.setState({ tags });
    };

    showInput = () => {
        this.setState({ inputVisible: true }, () => this.input.focus());
    };

    handleInputChange = e => {
        this.setState({ inputValue: e.target.value });
    };

    handleInputConfirm = () => {
        const { inputValue } = this.state;
        let { tags } = this.state;
        if (inputValue && tags.indexOf(inputValue) === -1) {
            tags = [...tags, inputValue];
        }
        console.log(tags);
        this.setState({
            tags,
            inputVisible: false,
            inputValue: '',
        });
    };

    handleEditInputChange = e => {
        this.setState({ editInputValue: e.target.value });
    };

    handleEditInputConfirm = () => {
        this.setState(({ tags, editInputIndex, editInputValue }) => {
            const newTags = [...tags];
            newTags[editInputIndex] = editInputValue;

            return {
                tags: newTags,
                editInputIndex: -1,
                editInputValue: '',
            };
        });
    };

    saveInputRef = input => {
        this.input = input;
    };

    saveEditInputRef = input => {
        this.editInput = input;
    };

    componentDidMount = () => {
        console.log(this.props.topicDetail)
        const { topicDetail } = this.props
        this.getKnowledgeListInfos()
        this.getDataAssetListInfos()
        let coverName = topicDetail.cover && topicDetail.cover.split("/")
        let logoName = topicDetail.logo && topicDetail.logo.split("/")
        if (topicDetail.tags) {//处理关键词回显
            this.setState({
              tags: topicDetail.tags.split(","),
            })
          }
        if (topicDetail.cover || topicDetail.logo) {
            this.setState({
                fileList: [
                    {
                        uid: -5,
                        name: coverName[coverName.length - 1],
                        status: 'done',
                        url: topicDetail.cover,
                    }
                ],
                fileList2: [
                    {
                        uid: -10,
                        name: logoName[logoName.length - 1],
                        status: 'done',
                        url: topicDetail.logo,
                    }
                ]
            })
        }
        this.setState({
            form: {
                name: topicDetail.name,
                introduction: topicDetail.introduction,
                cover: topicDetail.cover,
                logo: topicDetail.logo,
                tags: topicDetail.tags,
            },
            targetKeys2: topicDetail.knowledgeList ? topicDetail.knowledgeList.split(",").map(Number) : [],
            targetKeys: topicDetail.resourceList ? topicDetail.resourceList.split(",").map(Number) : [],
            formloading: true
        }, () => { console.log(this.state.targetKeys) })
    }

    getKnowledgeListInfos = () => {
        this.props.dispatch({
            type: "global/getKnowledgeListInfos",
            payload: {}
        }).then(res => {
            console.log(res)
            if (res) {
                res.data.map(item => {
                    item.key = item.id
                })
                this.setState({
                    keywordData2: res.data
                })
            }
        })
    }
    getDataAssetListInfos = () => {
        this.props.dispatch({
            type: "global/getDataAssetListInfos",
            payload: {}
        }).then(res => {
            console.log(res)
            if (res) {
                res.data.map(item => {
                    item.key = parseInt(item.id)
                })
                this.setState({
                    keywordData: res.data
                })
            }
        })
    }

    //校验通过提交
    submit = () => {
        let { form, cover, logo, targetKeys2, targetKeys,tags } = this.state
        this.setState({ loading: true })
        console.log(this.props)
        this.props.handleOk()
        this.props.dispatch({
            type: "global/saveTopic",
            payload: {
                ...form,
                cover: cover,
                logo: logo,
                resourceList: targetKeys.join(","),
                knowledgeList: targetKeys2.join(","),
                id: this.props.topicDetail.id,
                tags:tags.join(",")
            }
        }).then(res => {
            console.log(res)
            if (res) {
                message.success("更新成功!")
                this.props.getTopicList()
            }
        })
    }
    //校验失败
    onFinishFailed = (err) => {
        this.setState({ loading: true })
        console.log(err.values)
        message.warning("请填写完整！")
    }

    handleCancel = () => {
        this.props.handleCancel()
    }
    //表单字段改变
    handleValuesChange = (changedValues, allValues) => {
        console.log(allValues)
        this.setState({
            form: allValues
        },
            () => {
                console.log(this.state.form)
            }
        )
    }
    //两栏转移
    transferOnChange = (targetKeys, direction, moveKeys) => {//targetKeys永远是选择的项
        console.log(targetKeys, direction, moveKeys)
        this.setState({
            // keywordData:this.state.keywordData,
            targetKeys: targetKeys
        })
    }
    //两栏转移2
    transferOnChange2 = (targetKeys, direction, moveKeys) => {
        console.log(targetKeys, direction, moveKeys)
        this.setState({
            // keywordData:this.state.keywordData,
            targetKeys2: targetKeys
        })
    }

    //选中项发生改变  参数一个是左边的keys  一个右边的keys 
    transferOnSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
        console.log(sourceSelectedKeys, targetSelectedKeys)
    }
    //选中项发生改变2  参数一个是左边的keys  一个右边的keys 
    transferOnSelectChange2 = (sourceSelectedKeys, targetSelectedKeys) => {
        console.log(sourceSelectedKeys, targetSelectedKeys)
    }
    //搜索
    transferOnSearch = (dir, value) => {
        // console.log('search:', dir, value);
    }
    //搜索2
    transferOnSearch2 = (dir, value) => {
        console.log('search:', dir, value);
    }
    //列表滚动
    transferOnScroll = (direction, e) => {
        console.log('direction:', direction);
        console.log('target:', e.target);
    }

    render() {
        let { form, loading, keywordData, targetKeys, keywordData2, targetKeys2, formloading,
            fileList, previewVisible, previewTitle, previewImage,
            fileList2, previewVisible2, previewTitle2, previewImage2,
            tags,inputVisible, inputValue, editInputIndex, editInputValue  } = this.state

        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>更换</div>
            </div>
        );
        return (
            <div className={styles.form}>
                {
                    formloading ?
                        <Form
                            name="form"
                            initialValues={form}
                            autoComplete="off"
                            labelAlign="right"
                            onFinish={this.submit}
                            onFinishFailed={this.onFinishFailed}
                            scrollToFirstError={true}
                            onValuesChange={this.handleValuesChange}
                        >
                            <div style={{ background: "#F2F2F2", padding: "8px 0" }}>
                                <div style={{ margin: "20px", background: "white" }}>
                                    <div className={styles.formItem}>
                                        <Row gutter={200}>
                                            <Col span={22} offset={1}>
                                                <Form.Item name="name" label="专题名称"
                                                    rules={[{ required: true, message: '请输入专题名称', },]}>
                                                    <Input placeholder="请输入专题名称" value={form.name} />
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </div>
                                </div>
                                <div style={{ margin: "20px", background: "white" }}>
                                    <div className={styles.formItem}>
                                        <Row gutter={200}>
                                            <Col span={22} offset={1}>
                                                <Form.Item name="introduction" label="专题摘要"
                                                    rules={[{ required: true, message: '请输入专题摘要', },]}>
                                                    <TextArea placeholder="请输入专题摘要" rows={5} value={form.introduction} maxLength={200} showCount />
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </div>
                                </div>
                                <div style={{ margin: "20px", background: "white" }}>
                                    <div className={styles.formItem}>
                                        <Row  >
                                            <Col span={11} offset={1}>
                                                <Form.Item label="封面">
                                                    <Upload
                                                        action={`http://${window.location.host}/api/jyk/file/upload`}
                                                        headers={{'p-user-token':sessionStorage.getItem("token")}}
                                                        listType="picture-card"
                                                        fileList={fileList}
                                                        maxCount={1}
                                                        onPreview={this.handlePreview1}
                                                        onChange={this.handleChange1}
                                                    >
                                                        {fileList.length >= 2 ? null : uploadButton}
                                                    </Upload>
                                                    <Modal
                                                        visible={previewVisible}
                                                        title={previewTitle}
                                                        footer={null}
                                                        onCancel={this.handleCancel1}
                                                    >
                                                        <img alt="example" style={{ width: '100%' }} src={previewImage} />
                                                    </Modal>
                                                </Form.Item>
                                            </Col>
                                            <Col span={11} >
                                                <Form.Item label="logo">
                                                    <Upload
                                                        action={`http://${window.location.host}/api/jyk/file/upload`}
                                                        headers={{'p-user-token':sessionStorage.getItem("token")}}
                                                        listType="picture-card"
                                                        fileList={fileList2}
                                                        maxCount={1}
                                                        onPreview={this.handlePreview2}
                                                        onChange={this.handleChange2}
                                                    >
                                                        {fileList2.length >= 2 ? null : uploadButton}
                                                    </Upload>
                                                    <Modal
                                                        visible={previewVisible2}
                                                        title={previewTitle2}
                                                        footer={null}
                                                        onCancel={this.handleCancel2}
                                                    >
                                                        <img alt="example" style={{ width: '100%' }} src={previewImage2} />
                                                    </Modal>
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </div>
                                </div>
                                <div style={{ margin: "20px", background: "white" }}>
                                    <div className={styles.formItem}>
                                        <Row>
                                            <Col span={22} offset={1}>
                                                <Form.Item label="资产筛选">
                                                    <Transfer
                                                        showSearch
                                                        dataSource={keywordData}
                                                        titles={['未选词汇', '已选词汇']}
                                                        operations={['已选词汇', '未选词汇']}
                                                        targetKeys={targetKeys}
                                                        listStyle={({
                                                            background: "#F2F2F2",
                                                            width: "750px",
                                                        })}
                                                        // onSearch={this.transferOnSearch}
                                                        onChange={this.transferOnChange}
                                                        onSelectChange={this.transferOnSelectChange}
                                                        onScroll={this.transferOnScroll}
                                                        render={item => item.title}
                                                    />
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </div>
                                </div>
                                <div style={{ margin: "20px", background: "white" }}>
                                    <div className={styles.formItem}>
                                        <Row>
                                            <Col span={22} offset={1}>
                                                <Form.Item label="科研软件筛选">
                                                    <Transfer
                                                        showSearch
                                                        dataSource={keywordData2}
                                                        operations={['已选词汇', '未选词汇']}
                                                        targetKeys={targetKeys2}
                                                        listStyle={{
                                                            background: "#F2F2F2",
                                                            width: "750px"
                                                        }}
                                                        // onSearch={this.transferOnSearch2}
                                                        onChange={this.transferOnChange2}
                                                        onSelectChange={this.transferOnSelectChange2}
                                                        onScroll={this.transferOnScroll}
                                                        render={item => item.title}
                                                    />
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </div>
                                </div>
                                <div style={{ margin: "20px", background: "white" }}>
                                    <div className={styles.formItem}>
                                        <Row>
                                            <Col span={10} offset={1}>
                                                <Form.Item name="tags" label="标签名">
                                                    {
                                                        tags.map((tag, index) => {
                                                            if (editInputIndex === index) {
                                                                return (
                                                                    <Input
                                                                        ref={this.saveEditInputRef}
                                                                        key={tag}
                                                                        size="small"
                                                                        className="tag-input"
                                                                        value={editInputValue}
                                                                        onChange={this.handleEditInputChange}
                                                                        onBlur={this.handleEditInputConfirm}
                                                                        onPressEnter={this.handleEditInputConfirm}
                                                                    />
                                                                );
                                                            }

                                                            const isLongTag = tag.length > 20;

                                                            const tagElem = (
                                                                <Tag
                                                                    className="edit-tag"
                                                                    key={tag}
                                                                    color="purple"
                                                                    closable
                                                                    onClose={() => this.handleClose(tag)}
                                                                >
                                                                    <span
                                                                        onDoubleClick={e => {
                                                                            if (index !== 0) {
                                                                                this.setState({ editInputIndex: index, editInputValue: tag }, () => {
                                                                                    this.editInput.focus();
                                                                                });
                                                                                e.preventDefault();
                                                                            }
                                                                        }}
                                                                    >
                                                                        {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                                                                    </span>
                                                                </Tag>
                                                            );
                                                            return isLongTag ? (
                                                                <Tooltip title={tag} key={tag}>
                                                                    {tagElem}
                                                                </Tooltip>
                                                            ) : (
                                                                tagElem
                                                            );
                                                        })
                                                    }
                                                    {
                                                        inputVisible && (
                                                            <Input
                                                                ref={this.saveInputRef}
                                                                type="text"
                                                                size="small"
                                                                className="tag-input"
                                                                value={inputValue}
                                                                onChange={this.handleInputChange}
                                                                onBlur={this.handleInputConfirm}
                                                                onPressEnter={this.handleInputConfirm}
                                                            />
                                                        )
                                                    }
                                                    {!inputVisible && (
                                                        <Tag className="site-tag-plus" onClick={this.showInput}>
                                                            <PlusOutlined />
                                                        </Tag>
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </div>
                                </div>
                                <div style={{ textAlign: "center" }}>
                                    <Button onClick={this.handleCancel}>取消</Button>
                                    <Button type="primary" style={{ marginLeft: "20px" }} htmlType="submit" loading={loading}>保存</Button>
                                </div>
                            </div>
                        </Form> : ""
                }
            </div>
        );
    }
}

export default CreateSpecialTopicForm;